﻿using PhotoGallery.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace PhotoGallery.Data.Repository
{
    public class AudioRepository : BaseRepository
    {
        private List<Audio> audioList;
        private XDocument doc;
        string path;
        Album album;

        public AudioRepository(Album currentAlbum, string owner)
        {
            Owner = owner;
            album = currentAlbum;
            string albumFolder = getAlbumFolder(album);
            LoadData(album.ID, albumFolder);
        }

        public AudioRepository(int albumID, string owner, string albumFolder)
        {
            Owner = owner;
            LoadData(albumID, albumFolder);
        }

        public IEnumerable<Audio> Get()
        {
            return audioList;
        }

        public Audio Get(int id)
        {
            return audioList.FirstOrDefault(m => m.ID == id);
        }

        public Audio GetFirst()
        {
            return audioList.FirstOrDefault();
        }

        public void Create(Audio audio)
        {
            audio.ID = GetMaxValue() + 1;
            audio.UploadedOn = DateTime.UtcNow;
            
            
            audioList.Add(audio);
            doc.Root.Add(new XElement("audio",
                              new XElement("id", audio.ID),
                              new XElement("title", audio.Title),
                              new XElement("filename", audio.FileName),
                              new XElement("thumbnail", audio.Thumbnail),
                              new XElement("description", audio.Description),
                              new XElement("uploadedOn", ConvertDate(audio.UploadedOn)),
                              new XElement("modifiedOn", null),
                              new XElement("deletedOn", null),
                              new XElement("shared", audio.Shared),
                              new XElement("orderNumber", GetMaxOrderNumber() + 1),
                              new XElement("active", true)
                              ));

            doc.Save(path + Settings.AudioMetaDataXml);

        }

        public void Update(Audio audio)
        {
            audio.ModifiedOn = DateTime.UtcNow;
            XElement node = doc.Root.Elements("audio").Where(i => (int)i.Element("id") == audio.ID).FirstOrDefault();

            node.SetElementValue("id", audio.ID);
            node.SetElementValue("title", audio.Title ?? "");
            node.SetElementValue("filename", audio.FileName ?? "");
            node.SetElementValue("thumbnail", audio.Thumbnail ?? "");
            node.SetElementValue("description", audio.Description ?? "");
            node.SetElementValue("modifiedOn", ConvertDate(audio.ModifiedOn) ?? ConvertDate(DateTime.UtcNow));
            node.SetElementValue("shared", (int)audio.Shared);

            doc.Save(path + Settings.AudioMetaDataXml);
        }

        public void Delete(Audio audio)
        {
            audio.DeletedOn = DateTime.UtcNow;
            XElement node = doc.Root.Elements("audio").Where(i => (int)i.Element("id") == audio.ID).FirstOrDefault();

            node.SetElementValue("deletedOn", ConvertDate(audio.DeletedOn));
            node.SetElementValue("active", false);

            doc.Save(path + Settings.AudioMetaDataXml);
        }

        public void Erise(int id)
        {
            doc.Root.Elements("audio").Where(i => (int)i.Element("id") == id).Remove();
            doc.Save(path + Settings.AudioMetaDataXml);
        }

        #region privateMethods

        private int GetMaxValue()
        {
            int count = doc.Descendants("audio").Count();
            if (count > 0)
            {
                var maxID = (from prod in doc.Descendants("audio")
                             select
                             (
                                         int.Parse(prod.Element("id").Value)
                             )).Max();

                return maxID;
            }
            else
            {
                return 0;
            }
        }

        private int GetMaxOrderNumber()
        {
            int count = doc.Descendants("audio").Count();
            if (count > 0)
            {
                var maxID = (from prod in doc.Descendants("audio")
                             select
                             (
                                         int.Parse(prod.Element("orderNumber").Value)
                             )).Max();

                return maxID;
            }
            else
            {
                return 0;
            }
        }

        private void LoadData(int albumID, string albumFolder = "")
        {
            audioList = new List<Audio>();
            string albumUrl = "/Audio/";

            //if (String.IsNullOrEmpty(albumFolder))
            //{
            //    album = new AlbumRepository(Owner).Get(albumID);
            //    path = BasePath + Settings.UploadsFolder + Owner + "\\Audio\\" + getAlbumFolder(album);
            //    albumUrl += getAlbumUrl(album);
            //}
            //else
            //{
                path = BasePath + Settings.UploadsFolder + Owner + "\\Audio\\" + albumFolder + "\\";
                albumUrl += albumFolder + "/";
            //}
            doc = XDocument.Load(path + Settings.AudioMetaDataXml);
            var qry = from audio in doc.Descendants("audio")
                      select new Audio(
                                         Convert.ToInt32(audio.Element("id").Value),
                                         audio.Element("title").Value,
                                         audio.Element("filename").Value,
                                         audio.Element("thumbnail").Value,
                                         audio.Element("description").Value,
                                         ConvertDate(audio.Element("uploadedOn").Value),
                                         ConvertDate(audio.Element("modifiedOn").Value),
                                         ConvertDate(audio.Element("deletedOn").Value),
                                         (SharedAlbum)Enum.Parse(typeof(SharedAlbum), audio.Element("shared").Value),
                                         Convert.ToInt32(audio.Element("orderNumber").Value),
                                         audio.Element("active").Value == "false" ? false : true
                                       );
            audioList.AddRange(qry.Where(x => x.Active == true).OrderByDescending(x => x.OrderNumber).ThenByDescending(x=>x.ID).ToList<Audio>());
        }

        #endregion
    }
}